package com.sybkl.bigdatastudentmybatisplus.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sybkl.bigdatastudentmybatisplus.entity.Table;
import com.sybkl.bigdatastudentmybatisplus.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/table")
public class TableController {

    @Autowired
    private TableService tableService;

    @GetMapping("/all")
    public List<Table> findAllStudent() {
        return tableService.list();
    }

    //班级人数
    @GetMapping("/{class_name}")
    public Integer findAllDataSize(@PathVariable String class_name) {
        QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_name", class_name);
        return tableService.list(queryWrapper).size();
    }


    @GetMapping("/page/{pageNum}/{pageSize}")
    public IPage<Table> findPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        IPage<Table> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
        return tableService.page(page, queryWrapper);
    }

    @GetMapping("/page")
    public IPage<Table> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String input) {
        IPage<Table> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
        //通过学生姓名或者班级进行模糊查询
        queryWrapper.like("name", input).or().like("class_name", input).or().like("id", input);
//        queryWrapper.orderByAsc("id");
        return tableService.page(page, queryWrapper);
    }

    //新增
    @PostMapping
    public boolean saveStudent(@RequestBody Table table) {
        return tableService.save(table);
    }

    //修改
    @PutMapping
    public boolean updateStudent(@RequestBody Table table) {
        return tableService.updateById(table);
    }

    //删除
    @DeleteMapping("/{id}")
    public boolean deleteStudent(@PathVariable String id) {
        return tableService.removeById(id);
    }

    //批量删除
    @PostMapping("/delete/batch")
    public boolean deleteBatchStudentInfo(@RequestBody List<String> ids) {
        return tableService.removeByIds(ids);
    }

    //导出
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws Exception {
        //从数据库查询所有的数据
        List<Table> tableList = tableService.list();

        //通过工具类创建writer写到磁盘路径
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "学号");
        writer.addHeaderAlias("className", "班级");
        writer.addHeaderAlias("name", "姓名");

        //一次性写出list内的对象到excel，使用默认样式，强制输出到标题
        writer.write(tableList, true);

        //设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("学生信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();
    }

    //导入
    @PostMapping("/import")
    public boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //通过JavaBean的方式读取excel内的对象
        //        List<Table> list = reader.readAll(Table.class);
        List<List<Object>> list = reader.read(1);
        List<Table> objects = CollUtil.newArrayList();

        for (List<Object> row : list) {
            Table table = new Table();
            table.setId(row.get(0).toString());
            table.setClassName(row.get(1).toString());
            table.setName(row.get(2).toString());
            objects.add(table);
        }
        //        System.out.println(list);
        tableService.saveBatch(objects);
        return true;
    }
}
